package com.dkm.orproject.dkmoa.action;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dkm.orproject.dkmoa.domain.OaLog;
import com.dkm.orproject.dkmoa.domain.OaPersonnel;
import com.dkm.orproject.dkmoa.domain.OaRegime;
import com.dkm.orproject.dkmoa.service.OaRegimeService;
import com.dkm.orproject.utils.jwt.login.UserLoginToken;
import com.dkm.orproject.utils.utils.FileTools;
import com.dkm.orproject.utils.utils.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *  @ClassName : OaRegimeAction  //类名
 *  @Description : 规章制度控制层
 *  @Author : zmh //作者
 *  @Date: 2020-11-10 09:28  //时间
 */
@RestController
@RequestMapping("/OaRegimeAction")
public class OaRegimeAction {

    /**
     * 工具类
     */
    @Resource
    Tools tools;

    /**
     * 文件上传工具类
     */
    @Autowired
    FileTools fileTools;

    /**
     * 规则制度服务层接口
     */
    @Resource
    private OaRegimeService oaRegimeService;

    /**
     * 操作人
     */
    OaPersonnel personnel;

    /**
     * 根据Id查询接口
     * @param pkRegimeId 规则制度id值
     * @param request 请求对象
     * @return 规章制度模型
     */
    @GetMapping("findById/{pkRegimeId}")
    @UserLoginToken
    public Map<String, Object> selectByPrimaryKey(@PathVariable("pkRegimeId") Long pkRegimeId, HttpServletRequest request) {
        OaPersonnel oaPersonnel = (OaPersonnel) request.getSession().getAttribute("user");
        Map<String, Object> map = new HashMap<>();
        try {
            OaRegime regime = oaRegimeService.selectByPrimaryKey(pkRegimeId);
            OaLog log = new OaLog();
            log.setLogTitle("规章制度id查询模块查询成功");
            log.setCreatedBy(oaPersonnel.getPersonnelName());
            log.setLogIp(request.getRemoteAddr());
            log.setLogType("1");
            log.setLogBody(JSON.toJSON(oaPersonnel).toString());
            tools.rowMap(map, 1, null);
            map.put("data", regime);
            return map;
        } catch (Exception e) {
            OaLog log = new OaLog();
            log.setLogTitle("规章制度根据id查询模块异常");
            log.setLogBody(JSON.toJSON(e.getStackTrace()).toString());
            log.setCreatedBy(oaPersonnel.getPersonnelName());
            log.setLogType("0");
            log.setLogIp(request.getRemoteAddr());
            tools.errorMap(map, log);
        }
        return map;
    }

    /**
     *根据Id删除该条数据接口
     * @param pkRegimeId
     * @param session 服务器会话
     * @param request 服务器请求
     * @return 回调函数
     */
    @UserLoginToken
    @DeleteMapping("deleteRegimeById/{pkRegimeId}")
    public Map<String, Object> deleteByPrimaryKey(@PathVariable("pkRegimeId") Long pkRegimeId, HttpSession session, HttpServletRequest request) {
        OaPersonnel oaPersonnel = (OaPersonnel) session.getAttribute("user");
        Map<String, Object> map = new HashMap<>();
        try {
            OaLog log = new OaLog();
            OaRegime oaRegime = new OaRegime();
            oaRegime.setPkRegimeId(pkRegimeId);
            oaRegime.setIsRevision("0");
            log.setCreatedBy(oaPersonnel.getPersonnelName());
            log.setLogTitle("新闻的删除模块");
            int rows = oaRegimeService.deleteByPrimaryKey(pkRegimeId);
            log.setLogIp(request.getRemoteAddr());
            log.setLogType("1");
            log.setLogBody(JSON.toJSON(oaPersonnel).toString());
            tools.rowMap(map, rows, log);
            return map;
        } catch (Exception e) {
            OaLog log = new OaLog();
            log.setLogTitle("规章制度的删除模块异常");
            log.setLogIp(request.getRemoteAddr());
            log.setLogBody(JSON.toJSON(e.getStackTrace()).toString());
            log.setCreatedBy(oaPersonnel.getPersonnelName());
            log.setLogType("0");
            tools.errorMap(map, log);
            return map;
        }


    }

    /**
     * 分页查询所有规则制度的接口
     * @param oaRegime
     * @param page 当前页数
     * @param limit 每页的行数
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param request 服务器请求对象
     * @return 所有规则制度的集合
     */
    @UserLoginToken
    @GetMapping("selectAll")
    public Map<String,Object> findAll(OaRegime oaRegime, Integer page, Integer limit, String startTime, String endTime, HttpServletRequest request){
        try {
            //查询总行数
            Long rowCount=oaRegimeService.rowCount(oaRegime,startTime,endTime);
            //分页查询集合
            List<OaRegime> logs=oaRegimeService.selectAll(oaRegime,startTime,endTime,page,limit);
            //返回集合
            return Tools.maps(logs,rowCount);
        } catch (Exception e) {
            OaPersonnel oaPersonnel= (OaPersonnel)request.getSession().getAttribute("user");
            Map<String,Object> map=new HashMap<>();
            OaLog log = new OaLog();
            log.setLogBody(JSONObject.toJSON(e.getStackTrace()).toString());
            log.setLogTitle("查询规则制度的所有方法");
            log.setLogType("0");
            log.setLogIp(request.getRemoteAddr());
            log.setCreatedBy(oaPersonnel.getPersonnelName());
            tools.errorMap(map,log);
            return map;
        }
    }

    /**
     * 批量删除规则制度的接口
     * @param ids 要删除的规则制度id数组
     * @param session 服务器会话对象
     * @param request 服务器请求对象
     * @return 回调函数
     */
    @DeleteMapping("deleteAll")
    @UserLoginToken
    public Map<String, Object> deleteAll(@RequestParam(value = "ids[]", required = false) Long[] ids, HttpSession session, HttpServletRequest request) {
        OaPersonnel user = (OaPersonnel) session.getAttribute("user");
        List<Long> list;
        Map<String,Object> map=new HashMap<>();
        if (ObjectUtils.isEmpty(ids)){
            return tools.rowMap(map,0,null);
        }else {
            //把数组转化为集合
            list = Arrays.asList(ids);
        }
        try {
            OaLog log = new OaLog();
            int deleteAll = oaRegimeService.deleteAll(list);
            log.setLogType("1");
            log.setLogIp(request.getRemoteAddr());
            log.setLogBody(JSONObject.toJSON(user).toString());
            log.setLogTitle("规章制度批量删除模块");
            log.setCreatedBy(user.getPersonnelName());
            tools.rowMap(map, deleteAll, log);
            map.put("data",deleteAll);
            return map;
        } catch (Exception e) {
            OaLog log = new OaLog();
            log.setCreatedBy(user.getPersonnelName());
            log.setLogIp(request.getRemoteAddr());
            log.setLogType("0");
            log.setLogBody(JSON.toJSON(e.getStackTrace()).toString());
            log.setLogTitle("规章制度删除模块异常");
            tools.errorMap(map,log);
            return map;
        }
    }

    /**
     * 修改和增加规章制度的接口
     * @param oaRegime 规则制度模型对象
     * @param request 请求对象
     * @return 回调函数
     */
    @PostMapping("updateOrAdd")
    @UserLoginToken
    public Map<String, Object> add(OaRegime oaRegime, HttpServletRequest request) {
        OaPersonnel oaPersonnel = (OaPersonnel) request.getSession().getAttribute("user");
        Map<String, Object> map = new HashMap<>();
        if (ObjectUtils.isEmpty(oaPersonnel)) {
            tools.rowMap(map, 0, null);
        }
        try {
            //获取oaRegime对象的OriginalFilename判断是否为空
            if (oaRegime.getFileOne().getOriginalFilename() != null && !"".equals(oaRegime.getFileOne().getOriginalFilename())) {
                //获得该文件的地址
                String path = fileTools.saveFile("regime", oaRegime.getFileOne());
                //把文件的地址路径设置到oaRegime对象里
                oaRegime.setRegimeFile(path);
            }
            int rows = 0;
            OaLog log = new OaLog();
            //如果id不为空 那么就修改 否则增加
            if (oaRegime.getPkRegimeId() != null && !"".equals(oaRegime.getPkRegimeId())) {
                //传入更新人
                oaRegime.setUpdatedBy(oaPersonnel.getPersonnelName());
                //传入更新时间
                oaRegime.setUpdatedTime(new Date());
                log.setLogTitle("制度修改模块");
                rows = oaRegimeService.updateByPrimaryKeySelective(oaRegime);
            } else {
                oaRegime.setCreatedBy(oaPersonnel.getPersonnelName());
                oaRegime.setIsRevision("1");
                log.setLogTitle("制度增加模块");
                rows = oaRegimeService.insertSelective(oaRegime);
            }
            log.setCreatedBy(oaPersonnel.getPersonnelName());
            log.setLogIp(request.getRemoteAddr());
            log.setLogBody(JSONObject.toJSON(oaPersonnel).toString());
            log.setLogType("1");
            tools.rowMap(map, rows, log);
            return map;
        } catch (Exception e) {
            OaLog log = new OaLog();
            log.setLogBody(JSONObject.toJSON(e.getStackTrace()).toString());
            log.setLogTitle("制度增加或修改模块异常");
            log.setCreatedBy(oaPersonnel.getPersonnelName());
            log.setLogType("0");
            log.setLogIp(request.getRemoteAddr());
            tools.errorMap(map, log);
            return map;
        }
    }
    /**
     * 日期格式化
     *
     * @param binder
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // true:允许输入空值，false:不能为空值
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
}
